package com.atguigu.auth.service.impl;

import com.atguigu.auth.service.SysMenuService;
import com.atguigu.auth.service.SysUserService;
import com.atguigu.model.system.SysUser;
import com.atguigu.security.custom.CustomUser;

import com.atguigu.security.custom.UserDetailsService;
import com.atguigu.vo.system.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author dale
 * @title UserDetailsServiceImpl
 * @date 2023/6/3 21:15
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查数据库，判断用户
        SysUser sysUser = sysUserService.getUserByUsername(username);
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }
        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        //查数据库，得到权限数据
        List<String> userPermsList = sysMenuService.findUserPermsByUserId(sysUser.getId());
        //封装一个集合，装权限数据,要求类型SimpleGrantedAuthority
        List<SimpleGrantedAuthority> authList=new ArrayList<>();
        //遍历集合
        for (String perms:userPermsList) {
            authList.add(new SimpleGrantedAuthority(perms.trim()));
        }
        //Collections.emptyList()       ????   放权限数据的
        return new CustomUser(sysUser, authList);
    }
}
